package com.ruoyi.common.datascope.aspect;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.enums.DataScopeEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class DataScopeAspect {

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataScope controllerDataScope) {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope)
    {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getSysUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
                dataScopeFilter(joinPoint, currentUser, controllerDataScope);
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user 用户
     * @param controllerDataScope 数据权限注解
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, DataScope controllerDataScope) {
        String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), SecurityContextHolder.getPermission());
        StringBuilder sqlString = new StringBuilder();
        List<String> conditions = new ArrayList<String>();
        String deptAlias = controllerDataScope.deptAlias();
        String userAlias = controllerDataScope.userAlias();
        String deptField = controllerDataScope.deptField();
        String userField = controllerDataScope.userField();
        boolean userFieldIsUserId = controllerDataScope.userFieldIsUserId();
        boolean hasCompanyId = controllerDataScope.hasCompanyId();
        boolean isBusiness = controllerDataScope.isBusiness();

        for (SysRole role : user.getRoles()) {
            String dataScope = role.getDataScope();
            if (!DataScopeEnum.DATA_SCOPE_CUSTOM.getVal().equals(dataScope) && conditions.contains(dataScope)) {
                continue;
            }
            if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions())
                    && !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))) {
                continue;
            }
            if (DataScopeEnum.DATA_SCOPE_ALL.getVal().equals(dataScope)) {
                sqlString = new StringBuilder();
                conditions.add(dataScope);
                break;
            }
            else if (DataScopeEnum.DATA_SCOPE_CUSTOM.getVal().equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " OR {}.{} IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, deptField, role.getRoleId()));
            }
            else if (DataScopeEnum.DATA_SCOPE_DEPT.getVal().equals(dataScope)) {
                sqlString.append(StringUtils.format(" OR {}.{} = {} ", deptAlias, deptField, user.getDeptId()));
            }
            else if (DataScopeEnum.DATA_SCOPE_DEPT_AND_CHILD.getVal().equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " OR {}.{} IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
                        deptAlias, deptField, user.getDeptId(), user.getDeptId()));
            }
            else if (DataScopeEnum.DATA_SCOPE_SELF.getVal().equals(dataScope)) {
                if (StringUtils.isNotBlank(userAlias)){
                    sqlString.append(StringUtils.format(" OR {}.{} = {} ", userAlias, userField, user.getUserId()));
                } else  {
                    if (isBusiness) {
                        // 数据权限为仅本人且没有userAlias别名, 则使用部门(业务)表别名再根据创建人匹配
                        sqlString.append(StringUtils.format(" OR {}.{} = {} ", deptAlias, userField, userFieldIsUserId ? user.getUserId() : user.getUserName()));
                    } else {
                        // 数据权限为仅本人且没有userAlias别名不查询任何数据
                        sqlString.append(StringUtils.format(" OR {}.{} = 0 ", deptAlias, deptField));
                    }

                }
            }
            conditions.add(dataScope);
        }

        // 多角色情况下，所有角色都不包含传递过来的权限字符，这个时候sqlString也会为空，所以要限制一下,不查询任何数据
        if (StringUtils.isEmpty(conditions))  {
            sqlString.append(StringUtils.format(" OR {}.{} = 0 ", deptAlias, deptField));
        }

        StringBuilder result = new StringBuilder();
        if (hasCompanyId) {
            //result.append(StringUtils.format("AND {}.company_id = {} ", deptAlias, user.getCompanyId()));
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                result.append( " AND (" + sqlString.substring(4) + ")");
                baseEntity.getParams().put(DATA_SCOPE, result.toString());
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint)
    {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
        {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_SCOPE, "");
        }
    }
}
